// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Collections.Generic;

namespace SnapObjects.Data
{
    public class TemplateImporter
    {
        public static int Import<TModel>(
            ICollection<IModelEntry<TModel>> dataSource,
            IDataTemplate template,
            string data)
        {
            var provider = new TemplateModelEntryImportProvider<TModel>(dataSource);

            return InternalImport<TModel>(provider, template, data);
        }

        public static int Import<TModel>(
            ICollection<TModel> dataSource,
            IDataTemplate template,
            string data)
        {
            var provider = new TemplateModelImportProvider<TModel>(dataSource);

            return InternalImport<TModel>(provider, template, data);
        }

        private static int InternalImport<TModel>(
            ITemplateImportProvider provider,
            IDataTemplate template,
            string data)
        {
            var engine = new DataTemplateEngine();

            var standardTemplate = engine.Convert(template);

            var templateParser = TemplateImportSchemaParserFactory.Create(template.DataFormat);

            var importSchema = templateParser.Parse(standardTemplate, provider);

            var dataParser = TemplateImportDataParserFactory.Create(template.DataFormat, typeof(TModel));

            var modelEntries = dataParser.Parse(data, importSchema);

            var count = provider.Import(modelEntries);

            return count;
        }
    }
}
